import axios from 'axios'
import { ElMessage } from 'element-plus'
const REQUEST_ID = 'X-Request-Id'

const instance = axios.create({
  // withCredentials: true,
  headers: {
    'Content-Type': 'application/json',
  },
  // timeout: 12000
})

instance.interceptors.request.use(
  (config) => {
    // config.headers[REQUEST_ID] = uuidv4()
    config.baseURL = 'http://papi.jslszc.cn'
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

instance.interceptors.response.use(
  (response) => {
    if (response.data.code && response.data.code !== 0) {
      ElMessage.error(response.data.msg || response.data.message)
    }
    return response
  },
  (err) => {
    const requestId = err?.config?.headers && err?.config?.headers[REQUEST_ID]
    if (requestId) {
      ElMessage(REQUEST_ID, '：', requestId)
    }
    ElMessage('url: ', err?.config?.url, `【${err?.config?.method}】 \n>>>> err: `, err)

    let description = '-'
    if (err.response?.data && err.response.data.message) {
      description = err.response.data.message
    }
    if (err.response?.data && err.response.data.result) {
      description = err.response.data.result.message
    }
    // @See: https://github.com/axios/axios/issues/383
    if (!err.response || !err.response.code) {
      ElMessage.error('The network is abnormal, please check the backend service and try again')
      return
    }
    if (err.response?.code !== 0) {
      ElMessage.error(`ERROR_CODE: ${err.response?.code}`)
    }
    // if (err.response?.status === 403) {
    //   // window.location.href = '/'
    // }
    if (err.response?.code === 401) {
      ElMessage.error(err.response)
    }

    return Promise.reject(err)
  }
)

export default instance
